package com.xtm.exercise.utils;


import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 说明：OkHttp工具类
 */
public class OkHttpUtils {
	private static final Logger logger = LoggerFactory.getLogger(OkHttpUtils.class);

	/**
	 * 定义客户端请求
	 */
	private static OkHttpClient client = new OkHttpClient().newBuilder()
			.connectTimeout(2, TimeUnit.MINUTES)   //连接时间
			.readTimeout(2, TimeUnit.MINUTES)      //超时时间
			.retryOnConnectionFailure(false)                //失败不再自动重试,避免第三方收到重复数据
			.build();

	//JSON数据格式
	public final static String APPLICATION_JSON = "application/json; charset=utf-8";

	private OkHttpUtils() {
	}

	/**
	 * Get 请求
	 *
	 * @param url 请求URL
	 * @return
	 * @throws Exception
	 */
	public static String okHttpGet(String url) throws Exception {
		return doGet(url, new HashMap<>(), new HashMap<>());
	}

	/**
	 * Get 请求
	 *
	 * @param url    请求URL
	 * @param header 请求头参数
	 * @param query  参数
	 * @return
	 * @throws Exception
	 */
	public static String okHttpGet(String url, Map<String, String> header, Map<String, String> query) throws Exception {
		return doGet(url, header, query);
	}

	/**
	 * Get请求
	 *
	 * @param url    url
	 * @param header 请求头参数
	 * @param query  参数
	 * @return
	 * @throws Exception
	 */
	public static String doGet(String url, Map<String, String> header, Map<String, String> query) throws Exception {
		try {
			// 创建一个请求
			Request.Builder builder = new Request.Builder();
			// 创建一个 request
			Request request = builder.url(url).build();
			// 创建一个 HttpUrl.Builder
			HttpUrl.Builder urlBuilder = request.url().newBuilder();
			// 创建一个 Headers.Builder
			Headers.Builder headerBuilder = request.headers().newBuilder();
			// 装载请求头参数
			Iterator<Map.Entry<String, String>> headerIterator = header.entrySet().iterator();
			headerIterator.forEachRemaining(e -> {
				headerBuilder.add(e.getKey(), e.getValue());
			});
			// 装载请求的参数
			Iterator<Map.Entry<String, String>> queryIterator = query.entrySet().iterator();
			queryIterator.forEachRemaining(e -> {
				urlBuilder.addQueryParameter(e.getKey(), e.getValue());
			});
			// 设置自定义的 builder
			builder.url(urlBuilder.build()).headers(headerBuilder.build());
			// 执行请求
			Response response = client.newCall(builder.build()).execute();
			if (!response.isSuccessful()) {
				throw new Exception("OkHttp连接失败!-doGet");
			} else {
				String responseBody = response.body().string();
				// 避免资源泄漏
				response.body().close();
				return responseBody;
			}
		} catch (Exception e) {
			logger.error("OkHttp连接失败!-doGet", e);
			throw new Exception("OkHttp连接失败!-doGet");
		}
	}

	public static BufferedImage doGet2(String url, Map<String, String> header, Map<String, String> query) throws Exception {
		try {
			// 创建一个请求
			Request.Builder builder = new Request.Builder();
			// 创建一个 request
			Request request = builder.url(url).build();
			// 创建一个 HttpUrl.Builder
			HttpUrl.Builder urlBuilder = request.url().newBuilder();
			// 创建一个 Headers.Builder
			Headers.Builder headerBuilder = request.headers().newBuilder();
			// 装载请求头参数
			Iterator<Map.Entry<String, String>> headerIterator = header.entrySet().iterator();
			headerIterator.forEachRemaining(e -> {
				headerBuilder.add(e.getKey(), e.getValue());
			});
			// 装载请求的参数
			Iterator<Map.Entry<String, String>> queryIterator = query.entrySet().iterator();
			queryIterator.forEachRemaining(e -> {
				urlBuilder.addQueryParameter(e.getKey(), e.getValue());
			});
			// 设置自定义的 builder
			builder.url(urlBuilder.build()).headers(headerBuilder.build());
			// 执行请求
			Response response = client.newCall(builder.build()).execute();
			if (!response.isSuccessful()) {
				throw new Exception("OkHttp连接失败!-doGet");
			} else {
				InputStream responseBody = response.body().byteStream();
				BufferedImage image = ImageIO.read(responseBody);
				// 避免资源泄漏
				response.body().close();
				return image;
			}
		} catch (Exception e) {
			logger.error("OkHttp连接失败!-doGet", e);
			throw new Exception("OkHttp连接失败!-doGet");
		}
	}

	/**
	 * post 请求
	 *
	 * @param url  请求URL
	 * @param json json格式数据
	 * @return
	 * @throws Exception
	 */
	public static String okHttpPostJson(String url, String json) throws Exception {
		return doPostJson(url, json, new HashMap<>(), new HashMap<>());
	}

	/**
	 * post 请求
	 *
	 * @param url    请求URL
	 * @param json   json格式数据
	 * @param header 请求头参数
	 * @param query  参数
	 * @return
	 * @throws Exception
	 */
	public static String okHttpPostJson(String url, String json, Map<String, String> header, Map<String, String> query) throws Exception {
		return doPostJson(url, json, header, query);
	}

	/**
	 * Post请求
	 *
	 * @param url    url
	 * @param json   json格式数据
	 * @param header 请求头参数
	 * @param query  参数
	 * @return
	 * @throws Exception
	 */
	public static String doPostJson(String url, String json, Map<String, String> header, Map<String, String> query) throws Exception {
		try {
			// 创建一个请求
			Request.Builder builder = new Request.Builder();
			// 创建一个 request
			Request request = builder.url(url).build();
			// 创建一个 HttpUrl.Builder
			HttpUrl.Builder urlBuilder = request.url().newBuilder();
			// 创建一个 Headers.Builder
			Headers.Builder headerBuilder = request.headers().newBuilder();
			// 装载请求头参数
			Iterator<Map.Entry<String, String>> headerIterator = header.entrySet().iterator();
			headerIterator.forEachRemaining(e -> {
				headerBuilder.add(e.getKey(), e.getValue());
			});
			// 装载请求的参数
			Iterator<Map.Entry<String, String>> queryIterator = query.entrySet().iterator();
			queryIterator.forEachRemaining(e -> {
				urlBuilder.addQueryParameter(e.getKey(), e.getValue());
			});
			// application/json
			RequestBody requestBody = RequestBody.create(MediaType.parse(APPLICATION_JSON), json);
			// 设置自定义的 builder
			builder.url(urlBuilder.build()).headers(headerBuilder.build()).post(requestBody);
			// 执行请求
			Response response = client.newCall(builder.build()).execute();
			if (!response.isSuccessful()) {
				throw new Exception("OkHttp连接失败!-doPost");
			} else {
				String responseBody = response.body().string();
				// 避免资源泄漏
				response.body().close();
				return responseBody;
			}
		} catch (Exception e) {
			logger.error("OkHttp连接失败!-doPost", e);
			throw new Exception("OkHttp连接失败!-doPost");
		}
	}

	/**
	 * Post请求
	 *
	 * @param url    url
	 * @param json   json格式数据
	 * @param header 请求头参数
	 * @param query  参数
	 * @return
	 * @throws Exception
	 */
	public static String doPostJson2(String url, String json, Map<String, String> header, Map<String, String> query) throws Exception {
		try {
			// 创建一个请求
			Request.Builder builder = new Request.Builder();
			// 创建一个 request
			Request request = builder.url(url).build();
			// 创建一个 HttpUrl.Builder
			HttpUrl.Builder urlBuilder = request.url().newBuilder();
			// 创建一个 Headers.Builder
			Headers.Builder headerBuilder = request.headers().newBuilder();
			// 装载请求头参数
			Iterator<Map.Entry<String, String>> headerIterator = header.entrySet().iterator();
			headerIterator.forEachRemaining(e -> {
				headerBuilder.add(e.getKey(), e.getValue());
			});
			// 装载请求的参数
			Iterator<Map.Entry<String, String>> queryIterator = query.entrySet().iterator();
			queryIterator.forEachRemaining(e -> {
				urlBuilder.addQueryParameter(e.getKey(), e.getValue());
			});
			// application/json
			RequestBody requestBody = RequestBody.create(MediaType.parse(APPLICATION_JSON), json);
			// 设置自定义的 builder
			builder.url(urlBuilder.build()).headers(headerBuilder.build()).post(requestBody);
			// 执行请求
			Response response = client.newCall(builder.build()).execute();
			if (!response.isSuccessful()) {
				throw new Exception("OkHttp连接失败!-doPost");
			} else {
				String responseBody = response.header("token");
				// 避免资源泄漏
				response.body().close();
				return responseBody;
			}
		} catch (Exception e) {
			logger.error("OkHttp连接失败!-doPost", e);
			throw new Exception("OkHttp连接失败!-doPost");
		}
	}
}
